#include "_SetFilepageCallback.h"
#include <QString>
#include "AnGlobal.h"
#include "AnAdbServer.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <iostream>
#include <QWidget>
#include <QFileDialog>
#include <QMessageBox>
#include <QDateTime>
#include <QtDebug>

_SetFilepageCallback::_SetFilepageCallback()
{

}

_SetFilepageCallback::_SetFilepageCallback(AnMainwin *anMainwin)
{
    amw=anMainwin;
    movie=new QMovie(":/img/loading.gif");
    dirStack=new QStringList();
    amw->fp->file_list->setColumnCount(4);
    header<<"名称"<<"类型"<<"大小(Byte)"<<"修改时间";
    amw->fp->file_list->setHorizontalHeaderLabels(header);
    amw->fp->file_list->setEditTriggers(QAbstractItemView::NoEditTriggers);
    amw->fp->file_list->setSelectionBehavior(QAbstractItemView::SelectRows);
    amw->fp->file_list->setShowGrid(false);
    amw->fp->file_list->setFocusPolicy(Qt::NoFocus);
    amw->fp->file_list->horizontalHeader()->setHidden(false);
    amw->fp->file_list->verticalHeader()->setHidden(true);
    amw->fp->file_list->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
    amw->fp->file_list->horizontalHeader()->resizeSection(0, 300);
    amw->fp->file_list->horizontalHeader()->setStretchLastSection(true);
    connect(amw->fp->file_list,SIGNAL(itemClicked(QTableWidgetItem *)),this,SLOT(set_current_item(QTableWidgetItem *)));
    connect(amw->fp->file_list,SIGNAL(itemDoubleClicked(QTableWidgetItem *)),this,SLOT(jump(QTableWidgetItem *)));

}

_SetFilepageCallback::~_SetFilepageCallback()
{

}

void _SetFilepageCallback::response(QJsonObject an_resp)
{
    std::cout << "response: \n" << QJsonDocument(an_resp).toJson().data() << std::endl;
    if(!QString::compare(an_resp.value(NAME).toString(),"file_list",Qt::CaseSensitive))
    {
        if(an_resp.value(DATA).toObject().value(RESULT).toInt())
        {
            currentDir=dirStack->last();
            amw->fp->file_list->clearContents();
            amw->fp->label_file_path->setText(CUR_PATH+currentDir);
            QJsonArray fileList=an_resp.value(DATA).toObject().value(FILES).toArray();
            int fileListSize=fileList.size()+1;
            amw->fp->file_list->setRowCount(fileListSize);
            amw->fp->file_list->setItem(0,0,new QTableWidgetItem(".."));
            amw->fp->file_list->setItem(0,1,new QTableWidgetItem(".."));
            amw->fp->file_list->setItem(0,2,new QTableWidgetItem(" "));
            amw->fp->file_list->setItem(0,3,new QTableWidgetItem(" "));
            amw->fp->file_list->item(0,0)->setIcon(QIcon(":/img/dir.png"));
            for(int i=0;i<fileListSize;i++)
            {
                amw->fp->file_list->setItem(i+1,0,new QTableWidgetItem(fileList[i].toObject().value(NAME).toString()));
                amw->fp->file_list->setItem(i+1,1,new QTableWidgetItem(fileList[i].toObject().value(TYPE).toString()));
                QString fileSize=QString::number(fileList[i].toObject().value(SIZE).toInt(),10);
                amw->fp->file_list->setItem(i+1,2,new QTableWidgetItem(fileSize));
                QDateTime updateTime=QDateTime::fromTime_t((long)fileList[i].toObject().value(UP_DATE).toDouble()/1000);
                amw->fp->file_list->setItem(i+1,3,new QTableWidgetItem(updateTime.toString("yyyy-MM-dd hh:mm:ss")));
                if(!QString::compare(fileList[i].toObject().value(TYPE).toString(),"dir",Qt::CaseSensitive))
                {
                    amw->fp->file_list->item(i+1,0)->setIcon(QIcon(":/img/dir.png"));
                }
                if(!QString::compare(fileList[i].toObject().value(TYPE).toString(),"file",Qt::CaseSensitive))
                {
                    amw->fp->file_list->item(i+1,0)->setIcon(QIcon(":/img/file.png"));
                }
            }
            amw->fp->file_list->sortItems(1,Qt::AscendingOrder);
            amw->fp->file_list->show();
        }
        else
        {
            firstMessageBox=new QMessageBox(amw);
            firstMessageBox->setIcon(QMessageBox::Icon::Critical);
            firstMessageBox->setText("获取文件列表失败");
            firstMessageBox->show();
        }
    }
    if(!QString::compare(an_resp.value(NAME).toString(),"file_export",Qt::CaseSensitive))
    {
        if(an_resp.value(DATA).toObject().value(RESULT).toInt())
        {
            firstDialog->close();
            firstMessageBox=new QMessageBox(amw);
            firstMessageBox->setIconPixmap(QPixmap(":/img/sign-check.png"));
            firstMessageBox->setText("导出成功");
            firstMessageBox->show();
        }
        else
        {
            firstDialog->close();
            delete firstDialog;
            firstMessageBox=new QMessageBox(amw);
            firstMessageBox->setIcon(QMessageBox::Icon::Critical);
            firstMessageBox->setText("导出失败");
            firstMessageBox->show();
        }
    }
    if(!QString::compare(an_resp.value(NAME).toString(),"file_import",Qt::CaseSensitive))
    {
        if(an_resp.value(DATA).toObject().value(RESULT).toInt())
        {
            firstDialog->close();
            delete firstDialog;
            firstMessageBox=new QMessageBox(amw);
            firstMessageBox->setIconPixmap(QPixmap(":/img/sign-check.png"));
            firstMessageBox->setText("导入成功");
            firstMessageBox->show();
            refresh_clicked();
        }
        else
        {
            firstDialog->close();
            delete firstDialog;
            firstMessageBox=new QMessageBox(amw);
            firstMessageBox->setIcon(QMessageBox::Icon::Critical);
            firstMessageBox->setText("导入失败");
            firstMessageBox->show();
        }
    }
}

void _SetFilepageCallback::connect_close()
{
    amw->fp->file_list->clearContents();
    dirStack->clear();
    amw->fp->label_file_path->setText(CUR_PATH);
}

void _SetFilepageCallback::connect_build()
{
    currentDir="";
    dirStack->append("/sdcard");
    QJsonObject reqs;
    reqs.insert(NAME, QJsonValue("file_list"));
    reqs.insert(STATUS, QJsonValue(REQUEST));
    QJsonObject data;
    data.insert(PATH,QJsonValue(dirStack->last()));
    reqs.insert(DATA,data);
    adb_server->adbServerManager(reqs, this);
    std::cout << "request: \n" << QJsonDocument(reqs).toJson().data() << std::endl;
}

void _SetFilepageCallback::refresh_clicked()
{
    amw->fp->file_list->clearContents();
    if(AnGlobal::is_connecting())
    {
        QJsonObject reqs;
        reqs.insert(NAME, QJsonValue("file_list"));
        reqs.insert(STATUS, QJsonValue(REQUEST));
        QJsonObject data;
        data.insert(PATH,QJsonValue(currentDir));
        reqs.insert(DATA,data);
        adb_server->adbServerManager(reqs, this);
        std::cout << "request: \n" << QJsonDocument(reqs).toJson().data() << std::endl;
    }
}

void _SetFilepageCallback::import_clicked()
{
    if(AnGlobal::is_connecting())
    {
        QString filePath=QFileDialog::getOpenFileName(amw, tr("打开"), "/home");
        if(filePath==NULL)
        {
            return;
        }
        QFileInfo temp=QFileInfo(filePath);
        QString fileName=temp.fileName();
        QByteArray aa=filePath.toLatin1();
        std::cout<<aa.data()<<std::endl;
        QJsonObject reqs;
        reqs.insert(NAME,QJsonValue("file_import"));
        reqs.insert(STATUS,QJsonValue(REQUEST));
        QJsonObject data;
        data.insert(LOC_PATH,QJsonValue(filePath));
        data.insert(REM_PATH,QJsonValue(currentDir+"/"+fileName));
        reqs.insert(DATA,data);
        adb_server->adbServerManager(reqs,this);
        std::cout << "request: \n" << QJsonDocument(reqs).toJson().data() << std::endl;
        firstDialog=new QDialog(amw);
        firstDialog->resize(300,100);
        firstDialog->setWindowFlags(Qt::FramelessWindowHint);
        firstDialog->setModal(true);
        firstDialog->move((amw->width()-firstDialog->width())/2,(amw->height()-firstDialog->height())/2);
        QLabel *movLabel=new QLabel(firstDialog);
        QLabel *diaLabel=new QLabel(firstDialog);
        diaLabel->setText("正在导入，请稍候...");
        diaLabel->setGeometry(100,25,150,50);
        movLabel->setMovie(movie);
        movLabel->setGeometry(50,25,50,50);
        firstDialog->open();
        movie->start();
    }
}

void _SetFilepageCallback::export_clicked()
{
    if(AnGlobal::is_connecting())
    {
        QTableWidgetItem *export_clicked_name=get_current_item();
        QTableWidgetItem *export_clicked_type=amw->fp->file_list->item(export_clicked_name->row(),1);
        QString itemName=export_clicked_name->text();
        QString itemType=export_clicked_type->text();
        if(!QString::compare(itemType,"file",Qt::CaseSensitive))
        {
            QString filePath=QFileDialog::getSaveFileName(amw, tr("保存"), "/home/"+itemName);

            if (filePath.isNull()) {
                return;
            }

            QJsonObject reqs;
            reqs.insert(NAME,QJsonValue("file_export"));
            reqs.insert(STATUS,QJsonValue(REQUEST));
            QJsonObject data;
            data.insert(LOC_PATH,QJsonValue(filePath));
            data.insert(REM_PATH,QJsonValue(currentDir+"/"+itemName));
            reqs.insert(DATA,data);
            adb_server->adbServerManager(reqs,this);
            std::cout << "request: \n" << QJsonDocument(reqs).toJson().data() << std::endl;
            firstDialog=new QDialog(amw);
            firstDialog->resize(300,100);
            firstDialog->setWindowFlags(Qt::FramelessWindowHint);
            firstDialog->setModal(true);
            firstDialog->move((amw->width()-firstDialog->width())/2,(amw->height()-firstDialog->height())/2);
            QLabel *movLabel=new QLabel(firstDialog);
            QLabel *diaLabel=new QLabel(firstDialog);
            diaLabel->setText("正在导出，请稍候...");
            diaLabel->setGeometry(100,25,150,50);
            movLabel->setMovie(movie);
            movLabel->setGeometry(50,25,50,50);
            firstDialog->open();
            movie->start();
        }
    }
}

void _SetFilepageCallback::set_current_item(QTableWidgetItem *item)
{
    current_item=amw->fp->file_list->item(item->row(),0);
}

QTableWidgetItem * _SetFilepageCallback::get_current_item()
{
    return current_item;
}

void _SetFilepageCallback::jump(QTableWidgetItem *item)
{
    if(AnGlobal::is_connecting())
    {
        if(item)
        {
            QTableWidgetItem *double_clicked_name=amw->fp->file_list->item(item->row(),0);
            QTableWidgetItem *double_clicked_type=amw->fp->file_list->item(item->row(),1);
            QString itemName=double_clicked_name->text();
            QString itemType=double_clicked_type->text();
            if(!QString::compare(itemType,"..",Qt::CaseSensitive))
            {
                if(QString::compare(currentDir,"/sdcard",Qt::CaseSensitive))
                {
                    dirStack->removeLast();
                    QJsonObject reqs;
                    reqs.insert(NAME, QJsonValue("file_list"));
                    reqs.insert(STATUS, QJsonValue(REQUEST));
                    QJsonObject data;
                    data.insert(PATH,QJsonValue(dirStack->last()));
                    reqs.insert(DATA,data);
                    adb_server->adbServerManager(reqs, this);
                    std::cout << "request: \n" << QJsonDocument(reqs).toJson().data() << std::endl;
                }
                else
                {
                    firstMessageBox=new QMessageBox(amw);
                    firstMessageBox->setIcon(QMessageBox::Icon::Warning);
                    firstMessageBox->setText("已经是最高级目录");
                    firstMessageBox->show();
                }
            }
            if(!QString::compare(itemType,"dir",Qt::CaseSensitive))
            {
                dirStack->append(currentDir+"/"+itemName);
                QJsonObject reqs;
                reqs.insert(NAME, QJsonValue("file_list"));
                reqs.insert(STATUS, QJsonValue(REQUEST));
                QJsonObject data;
                data.insert(PATH,QJsonValue(dirStack->last()));
                reqs.insert(DATA,data);
                adb_server->adbServerManager(reqs, this);
                std::cout << "request: \n" << QJsonDocument(reqs).toJson().data() << std::endl;
            }
        }
    }
}
